<script setup>
import { ref, watch, onMounted } from "vue";
import {
  getEmpList,
  addEmp,
  getEmpById,
  updateEmp,
  deleteEmp,
} from "@/api/emp";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { getDeptList } from "@/api/dept";

// token
const token = ref("");

// 定义搜索表单
const searchForm = ref({
  name: "",
  gender: "",
  entryDateRange: [],
  begin: "",
  end: "",
});

// 定义表格数据
const empList = ref([]);

// 职位映射关系
const jobMap = {
  1: "班主任",
  2: "讲师",
  3: "学工主管",
  4: "教研主管",
  5: "咨询师",
};

// 职位列表
const jobs = ref([
  { value: 1, name: "班主任" },
  { value: 2, name: "讲师" },
  { value: 3, name: "学工主管" },
  { value: 4, name: "教研主管" },
  { value: 5, name: "咨询师" },
]);

// 部门列表
const depts = ref([]);

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 控制对话框显示
const dialogVisible = ref(false);
const dialogTitle = ref("新增员工");

// 定义表单引用
const empFormRef = ref(null);
// 定义表单数据
const empForm = ref({
  username: "",
  name: "",
  gender: "",
  job: "",
  entryDate: "",
  deptId: "",
  phone: "",
  salary: "",
  image: "",
  exprList: [],
});

const ids = ref([]); // 选中的id集合

//表单校验规则
const rules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "用户名长度应在2到20个字符之间",
      trigger: "blur",
    },
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    {
      min: 2,
      max: 10,
      message: "姓名长度应在2到10个字符之间",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1\d{10}$/g, message: "请输入有效的手机号", trigger: "blur" },
  ],
});

// 添加工作经历
const addExpr = () => {
  empForm.value.exprList.push({
    company: "",
    job: "",
    begin: "",
    end: "",
    exprDateRange: [],
  });
};

// 监听工作经历日期变化
watch(
  () => empForm.value.exprList,
  (newVal) => {
    newVal.forEach((item) => {
      if (item.exprDateRange && item.exprDateRange.length === 2) {
        item.begin = item.exprDateRange[0];
        item.end = item.exprDateRange[1];
      } else {
        item.begin = "";
        item.end = "";
      }
    });
  },
  { deep: true }
);

// 监听搜索表单日期变化
watch(
  () => searchForm.value.entryDateRange,
  (newVal) => {
    if (newVal && newVal.length === 2) {
      searchForm.value.begin = newVal[0];
      searchForm.value.end = newVal[1];
    } else {
      searchForm.value.begin = "";
      searchForm.value.end = "";
    }
  }
);

// 搜索员工
const handleSearch = async () => {
  console.log("搜索表单：", searchForm.value);
  const params = {
    name: searchForm.value.name,
    gender: searchForm.value.gender,
    begin: searchForm.value.begin,
    end: searchForm.value.end,
    page: pagination.value.currentPage,
    PageSize: pagination.value.pageSize,
  };
  const res = await getEmpList(params);
  console.log(res);
  if (res.code) {
    empList.value = res.data.rows;
    pagination.value.total = res.data.total;
  } else {
    ElMessage.error(res.message);
  }
};

// 重置搜索表单
const handleReset = () => {
  searchForm.value = {
    name: "",
    gender: "",
    entryDateRange: [],
    begin: "",
    end: "",
  };
  handleSearch();
};

// 分页相关
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  handleSearch();
};
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  handleSearch();
};

// 保存员工
const save = async () => {
  // 1. 校验表单
  await empFormRef.value.validate();

  let res = null;

  // 根据id判断是新增还是编辑
  if (empForm.value.id) {
    // 编辑
    res = await updateEmp(empForm.value);
  } else {
    // 新增
    res = await addEmp(empForm.value);
  }
  if (res.code) {
    ElMessage.success("保存成功!");
    // 关闭对话框
    dialogVisible.value = false;
    // 刷新列表
    handleSearch();
  } else {
    ElMessage.error(res.msg);
  }
};

// 新增员工
const handleAdd = () => {
  // 1. 清空表单数据
  empForm.value = {
    username: "",
    name: "",
    gender: "",
    job: "",
    entryDate: "",
    deptId: "",
    phone: "",
    salary: "",
    image: "",
    exprList: [],
  };

  // 2. 设置标题
  dialogTitle.value = "新增员工";
  // 3. 打开对话框
  dialogVisible.value = true;

  if (empFormRef.value) {
    empFormRef.value.resetFields(); // 使用 resetFields 而不是 clearValidate
  }
};

// 编辑员工
const handleEdit = async (id) => {
  // 1. 根据id查询员工信息
  const res = await getEmpById(id);
  // 2. 填充表单数据
  if (res.code) {
    empForm.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
  // 3. 设置标题
  dialogTitle.value = "编辑员工";
  // 4.将工作经历的日期范围转换为数组
  empForm.value.exprList.forEach((expr) => {
    expr.exprDateRange = [expr.begin, expr.end];
  });
  // 5. 打开对话框
  dialogVisible.value = true;
  // 清空表单验证
  if (empFormRef.value) {
    empFormRef.value.clearValidate();
  }
};

// 获取选中的员工id数组
const handleSelectionChange = (selection) => {
  // 获取选中的员工id数组
  ids.value = selection.map((item) => item.id);
};

// 删除员工
const handleDelete = (ids) => {
  ElMessageBox.confirm("此操作将永久删除该员工, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 删除员工
    const res = await deleteEmp(ids);
    if (res.code) {
      ElMessage.success("删除成功!");
      // 刷新列表
      handleSearch();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要删除的员工!");
    return;
  }
  handleDelete(ids.value);
};

// 获取部门列表
const getDepts = async () => {
  // 获取部门列表
  const res = await getDeptList();
  if (res.code) {
    depts.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  empForm.value.image = response.data;
};
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("只支持上传图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("只能上传10M以内图片");
    return false;
  }
  return true;
};

// 钩子函数
onMounted(() => {
  handleSearch();
  getDepts();
  token.value = JSON.parse(localStorage.getItem("userInfo")).token;
});
</script>

<template>
  <h1>员工管理</h1>

  <!------------ 搜索表单 ------------>
  <el-form :model="searchForm" class="searchForm">
    <el-form-item label="姓名：" class="form-item">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入员工姓名"
        class="search-item"
        clearable="true"
      />
    </el-form-item>
    <el-form-item label="性别：" class="form-item">
      <el-select
        v-model="searchForm.gender"
        placeholder="请选择"
        class="search-item"
      >
        <el-option label="男" :value="1" />
        <el-option label="女" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期：" class="form-item">
      <el-date-picker
        v-model="searchForm.entryDateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        class="search-item"
      />
    </el-form-item>
    <el-form-item class="form-item-btn">
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>

  <!------------ 操作按钮 ------------>
  <div class="action-buttons">
    <el-button type="primary" size="large" :icon="Plus" @click="handleAdd">
      新增员工</el-button
    >
    <el-button
      type="danger"
      size="large"
      :icon="Delete"
      @click="handleBatchDelete"
      >批量删除</el-button
    >
  </div>

  <!------------ 表格和分页 ------------>
  <el-table
    :data="empList"
    border
    style="width: 100%; margin-top: 3px"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="75" align="center" />
    <el-table-column prop="name" label="姓名" width="150" align="center" />
    <el-table-column label="性别" width="80" align="center">
      <template #default="{ row }">
        {{ row.gender === 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column label="头像" width="160" align="center">
      <template #default="{ row }">
        <el-image
          :src="row.image"
          style="width: 50px; height: 50px; border-radius: 30%"
          fit="cover"
        />
      </template>
    </el-table-column>
    <el-table-column
      prop="deptName"
      label="部门名称"
      width="150"
      align="center"
    />
    <el-table-column label="职位" width="135" align="center">
      <template #default="{ row }">
        {{ jobMap[row.job] || "其他" }}
      </template>
    </el-table-column>
    <el-table-column
      prop="entryDate"
      label="入职日期"
      width="180"
      align="center"
    />
    <el-table-column
      prop="updateTime"
      label="最后操作时间"
      width="225"
      align="center"
    />
    <el-table-column label="操作" align="center">
      <template #default="{ row }">
        <el-button
          type="primary"
          class="action-button"
          size="medium"
          :icon="Edit"
          @click="handleEdit(row.id)"
          >编辑</el-button
        >
        <el-button
          type="danger"
          class="action-button"
          size="medium"
          :icon="Delete"
          @click="handleDelete(row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    style="margin-top: 20px"
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :total="pagination.total"
    layout="total, sizes, prev, pager, next, jumper"
    :page-sizes="[5, 10, 20, 30]"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!------------ 新增/修改员工对话框 ------------>
  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="empFormRef"
      :model="empForm"
      label-width="80px"
      :rules="rules"
    >
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="empForm.username"
              placeholder="请输入员工用户名，2-20个字"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="empForm.name"
              placeholder="请输入员工姓名，2-10个字"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="empForm.gender"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="empForm.phone"
              placeholder="请输入员工手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select
              v-model="empForm.job"
              placeholder="请选择职位"
              style="width: 100%"
            >
              <el-option
                v-for="(job, index) in jobs"
                :key="job.id"
                :label="job.name"
                :value="job.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input
              v-model="empForm.salary"
              placeholder="请输入员工薪资"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select
              v-model="empForm.deptId"
              placeholder="请选择部门"
              style="width: 100%"
            >
              <el-option
                v-for="(dept, index) in depts"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="empForm.entryDate"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :headers="{ token: token }"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="empForm.image" :src="empForm.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addExpr"
              >+ 添加工作经历</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row :gutter="3" v-for="(expr, index) in empForm.exprList">
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker
              type="daterange"
              v-model="expr.exprDateRange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input
              v-model="expr.company"
              placeholder="请输入公司名称"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button
              type="danger"
              style="
                margin-left: 15px;
                height: 25px;
                width: 60px;
                font-size: 15px;
              "
              @click="empForm.exprList.splice(index, 1)"
              >- 删除</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
h1 {
  color: blueviolet;
  /* 宋体 */
  font-family: "SimSun";
  font-size: 24px;
  font-weight: bold;
}

.searchForm {
  display: flex;
  align-items: center;
  margin-top: 12px;
  margin-bottom: 10px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-right: 45px;
}

/* 调整 el-form-item 的标签字体大小 */
:deep(.el-form-item__label) {
  font-size: 15px;
  /* 放大标签字体 */
  color: #606266;
}

.search-item {
  width: 280px;
  /* 放大表单项宽度 */
  font-size: 16px;
  /* 放大字体 */
}

.el-input__inner,
.el-select__input,
.el-date-editor .el-range-input {
  height: 40px;
  /* 放大输入框高度 */
  line-height: 40px;
  /* 确保文字垂直居中 */
  padding: 0 10px;
  /* 调整内边距 */
}

.el-button {
  height: 35px;
  /* 放大按钮高度 */
  font-size: 14px;
  /* 放大按钮字体 */
  padding: 0 16px;
  /* 调整按钮内边距 */
}

.form-item-btn {
  height: 18px;
  /* 调整按钮高度 */
  font-size: 12px;
  /* 调整按钮字体大小 */
  padding: 0 8px;
  /* 调整按钮内边距 */
  margin-right: 5px;
  /* 调整按钮之间的间距 */
  align-items: center;
  margin-left: 10px;
  /* 调整按钮之间的间距 */
}

.action-buttons {
  margin-top: 12px;
  margin-bottom: 18px;
  display: flex;
  gap: 10px;
  /* 按钮之间的间距 */
}

.el-button {
  height: 35px;
  font-size: 12px;
  padding: 0 20px;
  border-radius: 4px;
  /* 圆角 */
  transition: background-color 0.3s, border-color 0.3s;
  /* 过渡效果 */
}

.action-button {
  height: 28px;
  /* 调整按钮高度 */
  font-size: 14px;
  /* 调整按钮字体大小 */
  padding: 0 8px;
  /* 调整按钮内边距 */
  margin-right: 5px;
  /* 调整按钮之间的间距 */
  width: 70px;
}

.el-button--primary {
  background-color: #409eff;
  /* 主按钮背景色 */
  border-color: #409eff;
  /* 主按钮边框色 */
}

.el-button--primary:hover {
  background-color: #66b1ff;
  /* 主按钮悬停背景色 */
  border-color: #66b1ff;
  /* 主按钮悬停边框色 */
}

.el-button--danger {
  background-color: #f56c6c;
  /* 危险按钮背景色 */
  border-color: #f56c6c;
  /* 危险按钮边框色 */
}

.el-button--danger:hover {
  background-color: #ff7875;
  /* 危险按钮悬停背景色 */
  border-color: #ff7875;
  /* 危险按钮悬停边框色 */
}

.avatar {
  height: 38px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>
